package com.sheng.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.sheng.constant.Constant;
import com.sheng.entity.UserEntity;
import com.sheng.entity.UserTokenEntity;
import com.sheng.form.UserQueryParams;
import com.sheng.model.UserModel;
import com.sheng.model.UserTokenModel;
import com.sheng.service.UserService;
import com.sheng.utils.Assert;
import com.sheng.utils.UUIDTool;

/**
 * 用户操作相关接口实现类
 * 
 * @Service 注解必填，标注这是一个接口实现！！
 */
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired//spring 自动注入 = 新建对象\实例化
    private JdbcTemplate jdbcTemplate;
	
	@Override
	public void createUser(UserModel user) {
        String inserSql = "insert into biz_user "+
        		"(user_no, user_name, password, phone, user_type, sex, is_valid, is_deleted,create_time) "+
        		"values(?,?,?,?,?,?,?,?,?)";
        //insert into biz_user (user_no, user_name, password, phone, user_type, sex, is_valid, is_deleted,create_time) values(?,?,?,?,?,?,?,?,?)
       
        String userNo = user.getUserNo();
        String userName = user.getUserName();
        jdbcTemplate.update(inserSql, new Object[]{
        		userNo,
				userName,
				user.getPassword(),
				user.getPhone(),
				user.getUserType(),
				user.getSex(),
				Constant.isValid.Y,
				Constant.isDeleted.N,
				new Date()
		});
	}

	@Override
	public void removeUser(Integer userId) {
		String updateSql = "delete from biz_user where user_id =?";
		jdbcTemplate.update(updateSql,userId);
	}

	@Override
	public void updateUser(UserEntity user) throws Exception {
		
		String token = user.getToken();
		this.checkToken(token);
		
		String sql = "update biz_user set user_no=?,user_name=?,phone=?,user_type=?,sex=? where user_id =?";
		jdbcTemplate.update(sql, new Object[]{
				user.getUserNo(),
				user.getUserName(),
				user.getPhone(),
				user.getUserType(),
				user.getSex(),
				user.getUserId()
		});
	}

	@Override
	public UserModel getUser(Integer userId) {
		
		UserQueryParams userQuery = new UserQueryParams();
		userQuery.setUserId(userId);
		
		List<UserModel> list = findUserList(userQuery);
		
		UserModel user = null;
		if(list!=null&&list.size()>0){
			user = list.get(0);
		}else{
			user = new UserModel();
		}
		return user;
	}

	@Override
	public List<UserModel> findUserList(UserQueryParams userQueryParams) {
		
		String sql = "SELECT user_id,user_no,user_name,phone,user_type,sex,create_time FROM biz_user WHERE 1 = 1 ";
		
		Object[] params = new Object[4]; //4个参数
		int index = 0;
		if(userQueryParams.getUserId()!=null){
			sql += "and user_id =? ";
			params[index] = userQueryParams.getUserId();
			index++;
		}
//		if(userQueryParams.getUserName()!=null&&!userQueryParams.getUserName().equals("")){
		if(!StringUtils.isBlank(userQueryParams.getUserName())){
			sql += "and user_name =? ";
			params[index] = userQueryParams.getUserName();
			index++;
		}
//		if(userQueryParams.getUserNo()!=null&&!userQueryParams.getUserNo().equals("")){
		if(!StringUtils.isBlank(userQueryParams.getUserNo())) {
			sql += "and user_no=? ";
			params[index] = userQueryParams.getUserNo();
			index++;
		}
		
		if(!StringUtils.isBlank(userQueryParams.getPassword())) {
			sql += "and password=? ";
			params[index] = userQueryParams.getPassword();
			index++;
		}
		
		Object[] paramsEnd = new Object[index];  
        System.arraycopy(params, 0, paramsEnd, 0, index);
        
		final List<UserModel> result = new ArrayList<UserModel>();
		jdbcTemplate.query(sql,  
				paramsEnd,  
                new RowCallbackHandler() {  
                    public void processRow(ResultSet rs) throws SQLException { 
                		UserModel user = new UserModel();
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserNo(rs.getString("user_no"));
                        user.setUserName(rs.getString("user_name"));
                        user.setPhone(rs.getString("phone"));
                        user.setUserType(rs.getString("user_type"));
                        user.setSex(rs.getString("sex"));
                        user.setCreateTime(rs.getTimestamp("create_time"));
                        result.add(user);
                    }  
                });
		
		return result;
	}

	@Override
	public UserTokenEntity login(String userNo, String password) throws Exception {
		Assert.notBlank(userNo, "用户账号不能为空");
		Assert.notBlank(password, "用户密码不能为空");
		
		UserQueryParams userQueryParams = new UserQueryParams();
		userQueryParams.setUserNo(userNo);
		userQueryParams.setPassword(password);
		
		List<UserModel> userList = this.findUserList(userQueryParams);
		
		if(userList!=null&&userList.size()>0) {
			//登录成功,生成token
			UserModel userModel = userList.get(0);
			//生成token
			UserTokenModel userToken = this.createUserToken(userList.get(0).getUserId());
			
			UserTokenEntity userEntity = new UserTokenEntity();
			userEntity.setUserId(userModel.getUserId());
			userEntity.setUserName(userModel.getUserName());
			userEntity.setUserNo(userModel.getUserNo());
			//设置token
			userEntity.setToken(userToken.getToken());
			return userEntity;
		}
//		return null;
		throw new Exception("登录失败!!!");
	}
	
	
	private UserTokenModel createUserToken(Integer userId) {
		//清空旧数据
		String delSql = "delete from biz_user_token where user_id = ?";
		jdbcTemplate.update(delSql, userId);

		String token = UUIDTool.getUUID();
		Integer expireTime = 7;
		String insertSql = "insert into biz_user_token(user_id,token,expire_time,create_time) "
				+ "values(?,?,?,?)";
		
		jdbcTemplate.update(insertSql, new Object[] {
			userId,
			token,
			expireTime,//默认7天有效期
			new Date()
		});
		
		UserTokenModel userToken = new UserTokenModel();
		userToken.setUserId(userId);
		userToken.setToken(token);
		userToken.setExpireTime(expireTime);
		return userToken;
	}
	
	/**
	 * 检查token
	 * @param token
	 * @throws Exception
	 */
	private void checkToken(String token) throws Exception {
		if(StringUtils.isBlank(token)) {
			throw new Exception("token为空");
		}
		try {
			SqlRowSet rs = jdbcTemplate.queryForRowSet("select expire_time,create_time from biz_user_token where token = '"+token+"'");
			if(rs.next()) {
				//存在token对应记录
				Integer expireTime = rs.getInt("expire_time");
				Date createTime = rs.getTime("create_time");
				Date now = new Date();
				Date expireDate =  DateUtils.addDays(createTime,expireTime);
				
				if(expireDate.before(now)) {
					throw new Exception("token过期");
				}
			}else {
				throw new Exception("token不合法");
			}
		} catch (EmptyResultDataAccessException e) {
			throw new Exception("token不合法");
		}
		
	}
	
	

}
